<?php

namespace Admin\Controller;

use Admin\Controller\IndexController;
use Zend\Form\Annotation\AnnotationBuilder;
use Admin\Form\ReaderForm;
use Admin\Model\DBO\UserDBO;
use Admin\Model\DBO\ReaderDBO;
use Admin\Entity\User;
use Admin\Entity\Reader;
use Admin\Controller\UploadImage;
use Zend\Filter\Digits;

class AddNewReaderController extends IndexController {

    public $classTable;
    public $userTable;
    public $readerTable;
    public $form;

    public function getForm() {
        if (!$this->form) {
            $user = new ReaderForm();
            $builder = new AnnotationBuilder();
            $this->form = $builder->createForm($user);
        }

        return $this->form;
    }

    public function insertDataToForm($form) {
        $valueOfDay = array();
        $valueOfDay[0] = 'Ngày:';
        for ($i = 1; $i <= 31; $i++) {
            $valueOfDay[$i] = $i;
        }
        $form->get('day')->setOptions(
                array(
                    'value_options' => $valueOfDay,
                )
        );
        $valueOfMonth = array();
        $valueOfMonth[0] = 'Tháng:';
        for ($i = 1; $i <= 12; $i++) {
            $valueOfMonth[$i] = 'Tháng ' . $i;
        }
        $form->get('month')->setOptions(
                array(
                    'value_options' => $valueOfMonth,
                )
        );
        $valueOfYear = array();
        $valueOfYear[0] = 'Năm:';
        for ($i = 2012; $i >= 1905; $i--) {
            $valueOfYear[$i] = $i;
        }
        $form->get('year')->setOptions(
                array(
                    'value_options' => $valueOfYear,
                )
        );
        $yearLearnOption = array();
        for ($i = 2000; $i <= 2030; $i++) {
            $j = $i + 5;
            $yearLearnOption[$i . ' - ' . $j] = $i . ' - ' . $j;
        }
        $form->get('yearLearn')->setOptions(
                array(
                    'value_options' => $yearLearnOption,
                )
        );
        $allClass = $this->getClassTable()->getAllClass();
        $valueOptions = array();
        foreach ($allClass as $cl) {
            $valueOptions[$cl['classID']] = "( " . $cl['className'] . " ) " . $cl['description'];
        }

        $form->get('classID')->setOptions(
                array(
                    'value_options' => $valueOptions,
                )
        );
    }

    public function indexAction() {
        // kiem tra neu chua dang nhap thi quay ve lai trang dang nhap
        $this->checkRole2();
        // Lay thuc the dang nhap dua ra layout
        $this->layout()->identity = $this->getAuthService()->getIdentity();
        // Lay toan bo cac Lop tu bang tbl_Class va dua vao form

        $form = $this->getForm();
        $this->insertDataToForm($form);

        // Lấy danh sách bạn đọc đăng ký làm thẻ
        $readerDBO = new ReaderDBO($this->getServiceLocator());
        $paginator = $readerDBO->getAllNewReader();
        $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
        $paginator->setItemCountPerPage(7);
        $paginator->setPageRange(3);

        // Neu bam nut dang ky ban doc (isPost())
        $request = $this->getRequest();
        if ($request->isPost()) {
            $myMessage = array();
            $user = new User();
            $filterDigit = new Digits();
            $reader = new Reader;
            $nonFile = $request->getPost()->toArray();
            $File = $this->params()->fromFiles('profilePhoto');
            $fileRename = "";
            $dirUpload = "";

            if (isset($File['name']) && $File['name'] != null) {
                $toArrayFileName = explode('.', $File['name']);
                $fileType = end($toArrayFileName);
                $fileRename = $filterDigit->filter($nonFile['cardBarcode']) . '.' . $fileType;
                $dirUpload = getcwd() . '/public/img/profilePhotos';
                $data = array_merge(
                        $nonFile, array('fileupload' => $File['name'])
                );
                $form->setData($data);
            } else {
                $form->setData($nonFile);
            }
            if ($form->isValid()) {
                // Dua du lieu vao doi tuong Reader
                $reader->setDataReader($form->getData());
                // Dua du lieu vao doi tuong User
                $data = $form->getData();
                $user->setDataUser($data);
                $user->setBirthday($data['year'] . '-' . $data['month'] . '-' . $data['day']);
                $user->setUserName($reader->getCardBarcode());
                $user->setRoleId('4');
                if (isset($File['name']) && $File['name'] != null) {
                    $user->setProfilePhoto('/img/profilePhotos/' . $fileRename);
                }
                // Lu thong tin bạn doc vao bang user voi dieu kien khong duoc trung userName
                $userDBO = new UserDBO($this->getServiceLocator());
                if ($userDBO->saveUser($user)) {
                    if (isset($File['name']) && $File['name'] != null) {
                        $objectUpload = new UploadImage();
                        $objectUpload->upload($File, $form, $dirUpload, $fileRename);
                    }
                    // get userID and insert to lib_readers
                    $user = $userDBO->getUserID($user->userName);
                    $reader->setUserID($user->userID);
                    // save info reader to DB
                    if ($readerDBO->saveReader($reader)) {
                        $myMessage['saveOK'] = 'saveOK';
                    } else {
                        $myMessage['saveError'] = 'saveError';
                    }
                } else {
                    $myMessage['userExist'] = 'userExist';
                }
                $paginator = $readerDBO->getAllNewReader();
                $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
                $paginator->setItemCountPerPage(7);
                $paginator->setPageRange(3);
            } else {
                // Dua cac message error ra view
                foreach ($form->getMessages() as $value => $ms) {
                    $myMessage[$value] = $value;
                }
            }
            return array(
                'form' => $form,
                'myMessage' => $myMessage,
                'paginator' => $paginator,
            );
        }
        return array(
            'form' => $form,
            'paginator' => $paginator,
        );
    }

    /*
     * Lư thông bạn đọc
     */

    public function ciculationReaderAction() {
        $userID = $this->params()->fromRoute('id', 0);
        $userID = (int) $userID;
        if ($userID != 0) {
            $readerDBO = new ReaderDBO($this->getServiceLocator());
            $readerDBO->changeIsActiveStatus(1, $userID);
        }
        return $this->redirect()->toRoute('list-reader');
    }

    /*
     * Chỉnh sửa thông tin bạn đọc
     */

    public function editReaderAction() {
        $userID = (int) $this->params()->fromRoute('id', 0);
        if (!$userID) {
            return $this->redirect()->toRoute('add-new-reader');
        }
        $readerDBO = new ReaderDBO($this->getServiceLocator());
        $reader = new Reader();
        $reader->setDataReader($readerDBO->getInfoReaderFromUserID($userID));
        $form = $this->getForm();
        $this->insertDataToForm($form);
        $form->bind($reader);
        $form->get('register')->setAttribute('value', 'Chỉnh sửa');
        $request = $this->getRequest();
        if ($request->isPost()) {
            $nonFile = $request->getPost()->toArray();
            $File = $this->params()->fromFiles('profilePhoto');
            $fileRename = "";
            $dirUpload = "";
            if (isset($File['name']) && $File['name'] != null) {
                $toArrayFileName = explode('.', $File['name']);
                $fileType = end($toArrayFileName);
                $fileRename = $reader->getCardBarcode() . '.' . $fileType;
                $dirUpload = getcwd() . '/public/img/profilePhotos';
                $data = array_merge(
                        $nonFile, array('fileupload' => $File['name'])
                );
                $form->setData($data);
            } else {
                $form->setData($nonFile);
            }
            if ($form->isValid()) {
                $user = new User();
                $user->setDataUser($reader->getArrayCopy());
                $user->setBirthday($reader->year . '-' . $reader->month . '-' . $reader->day);
                $user->setUserName($reader->getCardBarcode());
                $user->setRoleId('4');
                if (isset($File['name']) && $File['name'] != null) {
                    $user->setProfilePhoto('/img/profilePhotos/' . $fileRename);
                }
                $objectUserDBO = new UserDBO($this->getServiceLocator());
                $objectUserDBO->updateUserInfo($user, $userID);
                if (isset($File['name']) && $File['name'] != null) {
                    $objectUpload = new UploadImage();
                    $objectUpload->upload($File, $form, $dirUpload, $fileRename);
                }
                $readerDBO->updateReaderInfo($reader, $userID);
                // Redirect to list of rooms
                return $this->redirect()->toRoute('add-new-reader');
            }
        }
        return array(
            'userID' => $userID,
            'form' => $form,
        );
    }

    /*
     * Xóa bạn đọc
     */

    public function deleteReaderAction() {
        
    }

    public function getClassTable() {
        if (!$this->classTable) {
            $sm = $this->getServiceLocator();
            $this->classTable = $sm->get('Admin\Model\ClassTable');
        }
        return $this->classTable;
    }

    public function getUserTable() {
        if (!$this->userTable) {
            $sm = $this->getServiceLocator();
            $this->userTable = $sm->get('Admin\Model\UserTable');
        }
        return $this->userTable;
    }

    public function getReaderTable() {
        if (!$this->readerTable) {
            $sm = $this->getServiceLocator();
            $this->readerTable = $sm->get('Admin\Model\ReaderTable');
        }
        return $this->readerTable;
    }

    public function upload($File, $form, $dirUpload, $fileRename = null) {
        $size = new Size(array('max' => 2000000)); //minimum bytes filesize
        $extention = new Extension(array('jpg', 'JPG', 'png', 'PNG', 'peg', 'PEG'));
        $adapter = new \Zend\File\Transfer\Adapter\Http();
        $adapter->setValidators(array($size, $extention), $File['name']);
        if (!$adapter->isValid()) {
            $dataError = $adapter->getMessages();
            $error = array();
            foreach ($dataError as $key => $row) {
                $error[] = $row;
            }
            $form->setMessages(array('fileupload' => $error));
        } else {
            $dir_upload = getcwd() . '/public/img/profilePhotos';
            $adapter->setDestination($dir_upload);
            $adapter->addFilter('Rename', $dirUpload . '/' . $rename);
            $adapter->receive($File['name']);
        }
    }

}